package com.diagnosis.record;

import android.app.Application;

import android.os.Bundle;
import android.os.Environment;

import android.util.Size;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.MediaStoreOutputOptions;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.common.util.concurrent.ListenableFuture;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        TextView tv = findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                starrtCamear();
            }
        });
        TextView tv2 = findViewById(R.id.tv2);
        tv2.setOnClickListener(view -> {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) previewView.getLayoutParams();
            layoutParams.width=500;
            layoutParams.height=500;
            layoutParams.leftMargin=200;
            layoutParams.topMargin=500;
            previewView.setLayoutParams(layoutParams);

        });

        TextView tv3 = findViewById(R.id.tv3);
        tv3.setOnClickListener(view -> {
            File outputDir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            File videoFile = new File(outputDir, "video_" + System.currentTimeMillis() + ".mp4");

            MediaStoreOutputOptions options = new MediaStoreOutputOptions.Builder(
                    getContentResolver(),
                    android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            )
                    .setContentValues(new android.content.ContentValues())
                    .build();

            recording = videoCapture.getOutput()
                    .prepareRecording(this, options)
                    .start(ContextCompat.getMainExecutor(this), event -> {
                        if (event instanceof VideoRecordEvent.Start) {
                            Toast.makeText(this, "录制开始", Toast.LENGTH_SHORT).show();
                        } else if (event instanceof VideoRecordEvent.Finalize) {
                            if (((VideoRecordEvent.Finalize) event).hasError()) {
                                Toast.makeText(this, "录制失败", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(this, "视频已保存: " + videoFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

        });
        TextView tv4 = findViewById(R.id.tv4);
        tv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (recording != null) {
                    recording.stop();
                    recording = null;
                }
            }
        });

        cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();



        Recorder recorder = new Recorder.Builder().build();
        videoCapture = VideoCapture.withOutput(recorder);
    }

    private VideoCapture<Recorder> videoCapture;
    private boolean isRecording = false;
    private Recording recording;

    private ProcessCameraProvider cameraProvider;
    private Preview previewUseCase;
    private PreviewView previewView;

    private CameraSelector cameraSelector;

    private void starrtCamear() {
        Application application = getApplication();
        ListenableFuture<ProcessCameraProvider> future = ProcessCameraProvider.getInstance(application);
        future.addListener(() -> {
            try {
                cameraProvider = future.get();
                if (cameraProvider != null) {
                    cameraProvider.unbindAll();
                    bindPreviewUseCase();
                }

            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, ContextCompat.getMainExecutor(application));
    }

    private void bindPreviewUseCase() {
        if (cameraProvider == null) {
            return;
        }
        if (previewUseCase != null) {
            cameraProvider.unbind(previewUseCase);
        }

        Preview.Builder builder = new Preview.Builder();
        builder.setTargetResolution(new Size(480, 640));

        previewUseCase = builder.build();

        previewView = new PreviewView(this);
        previewView.setImplementationMode(PreviewView.ImplementationMode.COMPATIBLE);

        previewUseCase.setSurfaceProvider(previewView.getSurfaceProvider());

        cameraProvider.bindToLifecycle(
                this,
                cameraSelector,
                previewUseCase,
                videoCapture
        );
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                300,
                300);
        layoutParams.leftMargin = 400;
        layoutParams.topMargin = 200;
        ViewGroup viewGroup = MainActivity.this.getWindow().getDecorView().findViewById(android.R.id.content);
        viewGroup.addView(previewView, layoutParams);
    }

}